<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>卷库管理</el-breadcrumb-item>
      <el-breadcrumb-item>试卷创编</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <el-form :model="form" ref="formRef" label-width="100px" :rules="formRules">
        <el-form-item label="章节：" prop="chapterId">
          <el-select v-model="form.chapterId">
            <el-option v-for="item in chapters" :key="item.chapterId" :value="item.chapterId" :label="item.chapterName"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="时间限制：" required >
          <el-date-picker v-model="form.limitDateTime" value-format="yyyy-MM-dd HH:mm:ss" type="datetimerange"
                          range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="试卷名称：" prop="examPaperName">
          <el-input v-model="form.examPaperName"/>
        </el-form-item>
        <el-form-item :key="index" :label="'标题'+(index+1)+'：'" required v-for="(titleItem, index) in form.titleItems">
          <el-input v-model="titleItem.name" style="width: 80%"/>
          <el-button type="text" style="margin-left: 20px" size="mini" @click="addQuestion(titleItem)">
            添加题目
          </el-button>
          <el-button type="text" size="mini" @click="form.titleItems.splice(index,1)">删除</el-button>
          <el-card class="exampaper-item-box" v-if="titleItem.questionItems.length!==0">
            <el-form-item :key="questionIndex" :label="'题目'+(questionIndex+1)+'：'"
                          v-for="(questionItem, questionIndex) in titleItem.questionItems" style="margin-bottom: 15px">
              <el-row>
                <el-col :span="23">
                  <QuestionShow :qType="questionItem.questionType" :question="questionItem"/>
                </el-col>
                <el-col :span="1">
                  <el-button type="text" size="mini" @click="titleItem.questionItems.splice(questionIndex,1)">删除</el-button>
                </el-col>
              </el-row>
            </el-form-item>
          </el-card>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm">提交</el-button>
          <el-button @click="resetForm">重置</el-button>
          <el-button type="success" @click="addTitle">添加标题</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-dialog :visible.sync="questionPage.showDialog" width="70%" @close="dialogClosed">
      <el-row>
        <el-col :span="4">
          <el-select v-model="questionPage.queryParam.chapterId" clearable @clear="query" @change="query" placeholder="请选择章节">
            <el-option v-for="item in chapters" :key="item.chapterId" :value="item.chapterId" :label="item.chapterName"></el-option>
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-select v-model="questionPage.queryParam.questionType" clearable @clear="query" @change="query" placeholder="请选择题型">
            <el-option v-for="item in questionType" :key="item.key" :value="item.key" :label="item.value"></el-option>
          </el-select>
        </el-col>
      </el-row>
      <el-table :data="questionPage.tableData"
                @selection-change="handleSelectionChange" border fit highlight-current-row style="width: 100%">
        <el-table-column type="selection" width="35"></el-table-column>
        <el-table-column prop="chapterId" label="章节" :formatter="chapterFormatter" width="280px"/>
        <el-table-column prop="questionType" label="题型" :formatter="questionTypeFormatter" width="70px"/>
        <el-table-column prop="shortTitle" label="题干" show-overflow-tooltip/>
      </el-table>
      <pagination v-show="questionPage.total>0" :total="questionPage.total"
                  :page.sync="questionPage.queryParam.pageIndex" :limit.sync="questionPage.queryParam.pageSize"
                  @pagination="search"/>
      <span slot="footer" class="dialog-footer">
          <el-button @click="questionPage.showDialog = false">取 消</el-button>
          <el-button type="primary" @click="confirmQuestionSelect">确定</el-button>
     </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapState, mapGetters } from 'vuex'
import questionApi from '@/api/question'
import examPaperApi from '@/api/examPaper'
import QuestionShow from '../question/components/Show'
import Pagination from '@/components/Pagination'
export default {
  
  components: { Pagination, QuestionShow },

  data() {
    return {
      form: {
        level: undefined,
        examPaperId: null,
        chapterId: null,
        examPaperName: '',
        titleItems: [],
      },
      formRules: {
        chapterId: [
          { required: true, message: '请选择章节', trigger: 'change' }
        ],
        examPaperName: [
          { required: true, message: '请输入试卷名称', trigger: 'blur' }
        ],
      },
      questionPage: {
        multipleSelection: [],
        showDialog: false,
        queryParam: {
          questionType: null,
          chapterId: null,
          level: null,
          pageIndex: undefined,
          pageSize: undefined
        },
        tableData: [],
        total: 0
      },
      currentTitleItem: null
    }
  },
  props: {
    mainLevel: {
      type: Number
    }
  },
  watch: {
    mainLevel() {
      this.resetForm()
    }
  },
  created() {
    this.form.level = this.mainLevel
    this.questionPage.queryParam.level = this.mainLevel
    let id = this.$route.query.id
    let _this = this
    if (id && parseInt(id) !== 0) {
      examPaperApi.select(id).then(re => {
        if (re.code === _this.ok.code) {
          _this.form = re.response
        }
      })
    }
  },
  methods: {
    addTitle () {
      this.form.titleItems.push({
        name: '',
        questionItems: []
      })
    },
    addQuestion (titleItem) {
      this.currentTitleItem = titleItem
      this.questionPage.showDialog = true
      this.query()
    },
    query() {
      this.questionPage.queryParam.pageIndex =  this.page.index
      this.questionPage.queryParam.pageSize = this.page.size
      this.search()
    },
    search () {
      questionApi.pageList(this.questionPage.queryParam).then(data => {
        if (data.code === this.ok.code) {
          this.questionPage.tableData = data.response.list
          this.questionPage.total = data.response.total
          this.questionPage.queryParam.pageIndex = data.response.pageNum
        }
      })
    },
    handleSelectionChange (val) {
      this.questionPage.multipleSelection = val
    },
    confirmQuestionSelect () {
      let _this = this
      this.questionPage.multipleSelection.forEach(q => {
        questionApi.select(q.questionId).then(re => {
          _this.currentTitleItem.questionItems.push(re.response)
        })
      })
      this.questionPage.showDialog = false
    },
    resetForm () {
      let lastId = this.form.examPaperId
      this.$refs['formRef'].resetFields()
      this.form = {
        examPaperId: null,
        level: null,
        chapterId: null,
        limitDateTime: [],
        examPaperName: '',
        titleItems: []
      }
      this.form.examPaperId = lastId
      this.form.level = this.mainLevel
      this.questionPage.queryParam.level = this.mainLevel
    },
    dialogClosed() {
      this.questionPage.queryParam.questionType = null,
      this.questionPage.queryParam.chapterId = null,
      this.questionPage.queryParam.level = this.mainLevel,
      this.questionPage.queryParam.pageIndex = undefined,
      this.questionPage.queryParam.pageSize = undefined,
      this.questionPage.tableData = []
    },
    submitForm () {
      let _this = this
      this.$refs.formRef.validate((valid) => {
        if (!valid) return
        examPaperApi.edit(this.form).then(re => {
          if (re.code === this.ok.code) {
            _this.$message.success(re.message)
            _this.$router.push('/exam/list')
          } else {
            _this.$message.error(re.message)
          }
        })
      })
    },
    questionTypeFormatter(row, column, cellValue, index) {
      return this.enumFormat(this.questionType, cellValue)
    },
    chapterFormatter(row, column, cellValue, index) {
      return this.chapterEnumFormat(cellValue)
    },
  },
  computed: {
    ...mapGetters('enumItem', [
      'enumFormat'
    ]),
    ...mapGetters('chapter', [
      'chapterEnumFormat'
    ]),
    ...mapState('page', {
      page: state => state.page
    }),
    ...mapState('chapter', {
      chapters: state => state.chapters
    }),
    ...mapState('resCode', {
      ok: state => state.OK
    }),
    ...mapState('enumItem', {
      questionType: state => state.question.typeEnum
    })
  }
}
</script>

<style lang="less" scoped>

</style>